<template>
    <view class="app-container init">
        <view class="init-loading flexrow">
            <u-loading-icon></u-loading-icon>
        </view>
        <up-popup :show="show" :closeOnClickOverlay="false">
            <view class="init-box">
                <view class="init-tit">
                    <text class="tit">主账号选择</text>
                </view>
                <view class="init-list">
                    <view class="init-item flexrow" v-for="(item, index) in list" :key="item.id" :class="{ active: active === index }" @tap="changeMerchant(index)">
                        <view class="text">
                            <text class="tit">商户名称：{{ item.name }}</text>
                            <text class="txt">商户地址：{{ item.detailAddress }}</text>
                            <text class="txt" v-if="item.status !== 'APPROVED'">审核状态：{{ status[item.status] }}</text>
                        </view>
                        <view class="icon">
                            <uni-icons type="checkbox-filled" size="20" color="#19be6b" v-if="active === index"></uni-icons>
                            <uni-icons type="checkbox" size="20" color="#999" v-else></uni-icons>
                        </view>
                    </view>
                </view>
                <view class="init-btn">
                    <up-button text="确认选择" type="success" @click="chooseMerchant"></up-button>
                </view>
            </view>
        </up-popup>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { login, merchantInfo } from '@/api/user.js'
import { merchantList } from '@/api/merchant.js'
import { showToast, linkto } from '@/utils/util'

const store = useStore()
const isLogin = computed(() => store.state.user.isLogin)
const code = ref('')

const show = ref(false)
const list = ref([])
const active = ref(0)

const status = ref({
    'APPROVING': '待审核',
    'APPROVED': '已审核',
    'REJECTED': '审核不通过',
    'DISABLED': '已停用',
})

const tempid = ref('')
const loading = ref(false)

onLoad(async (option) => {
    store.commit('user/setParams', {
        token: '',
        merchantId: ''
    })
    
    if (option.scene) {
        const scene = decodeURIComponent(option.scene)
        const temp = scene.split('=')
        if (temp.length >= 2) {
            tempid.value = temp[1]
        }
    }
    
    await getCode()
    toLogin()
})

const getCode = () => {
    return new Promise((resolve, reject) => {
        uni.login({
            provider: 'weixin',
            success: res => {
                code.value = res.code
                resolve(res.code)
            }
        })
    })
}

const toLogin = () => {
    const params = {
        code: code.value,
        channel: 'MERCHANT'
    }
    if (tempid.value) {
        params.merchantId = tempid.value
    }
    loading.value = true
    login(params).then(res => {
        loading.value = false
        store.commit('user/setParams', {
            token: res.token
        })
        getMerchant()
    }).catch(e => {
        loading.value = false
    })
}

const getMerchant = () => {
    merchantList().then(res => {
        const _list = res.records || []
        if (_list.length) {
            list.value = _list
            show.value = true
        } else {
            uni.reLaunch({
                url: '/pages/user/join'
            })
        }
    })
}

const changeMerchant = (index) => {
    active.value = index
}

const chooseMerchant = () => {
    const obj = list.value[active.value]
    if (obj.status !== 'APPROVED') {
        showToast('无法选择非正常状态的商户')
        return false
    }
    store.commit('user/setParams', {
        merchantId: obj.id,
        mainUser: obj.mainUser
    })
    show.value = false
    getInfo()
}

const getInfo = () => {
    merchantInfo().then(res => {
        store.commit('user/setParams', {
            company: res.companyName,
            address: res.address,
            sellTotal: res.sellTotal,
            rentingTotal: res.rentingTotal,
            depositTotal: res.depositTotal,
            balance: res.balance,
            rentable: res.rentable,
            marketable: res.marketable
        })
        uni.switchTab({
            url: '/pages/home/order'
        })
    })
}
</script>

<style lang="scss">
.init {
    &-loading {
        height: 100vh;
        justify-content: center;
        align-items: center;
    }
    &-box {
        padding: 0 $zzk-margin;
    }
    &-tit {
        .tit {
            font-size: 32rpx;
            line-height: 96rpx;
            font-weight: 700;
        }
    }
    &-item {
        background-color: #f5f5f5;
        border-radius: 16rpx;
        padding: 20rpx;
        margin-bottom: 20rpx;
        align-items: center;
        border: #f5f5f5 2rpx solid;
        &.active {
            border-color: $u-success;
            background-color: $u-success-light;
        }
        .tit {
            font-size: 28rpx;
            line-height: 48rpx;
        }
        .txt {
            font-size: 28rpx;
            line-height: 48rpx;
            color: #999;
        }
        .text {
            flex: 1;
        }
    }
    &-btn {
        padding: 20rpx 0;
    }
}
</style>